﻿package components {
	import flash.display.*;
	import flash.events.*;
	import flash.geom.*;
	
	import gs.*;
	import gs.easing.*;

	public class Menu extends Sprite 
	{
		static private var FLAG:Boolean;
		
		private var subMenuList:Vector.<Menu> = new Vector.<Menu>();
		private var layout:Object;
		
		// 팩토리 메서드로만, 생성가능하게 무력화 시킴.
		public function Menu(): void { if(!FLAG) throw new Error('왠만하면 팩토리써요'); }
		
		static public function create(layout:Object, $visible:Boolean = false): Menu
		{
			FLAG = true;
			var menu:Menu = new Menu;
			FLAG = false;
			menu.visible = $visible;
			menu.setLayout(layout);
			menu.x = layout.position.x;
			menu.y = layout.position.y;
			return menu;
		}
		
		// protocol : Interface 수정되야됨. button 간격, 생성포인트, 타겟포인트, 알파값, 다이렉트
		public final function setLayout(layout:Object): void { this.layout = layout; }
		
		// 열림 효과.
		public final function open(e:Event=null): void
		{	
			enabledVisible();
			this.alpha = 0;
			TweenLite.to(this, 0.2, {x:layout.target.x, y:layout.target.y, alpha:1, ease:gs.easing.Cubic });
		}
		// 닫힘 효과.
		public final function close(e:Event=null): void
		{
			this.alpha = 1;
			TweenLite.to(this, 0.2, {x:layout.position.x, y: layout.position.y, alpha:0, ease:gs.easing.Cubic , onComplete:disabledVisible });
			closeAllSub();
		}
		// 서브메뉴 전부 다 닫히게 함.
		public final function closeAllSub(e:Event=null): void
		{
			for each(var menu:Menu in subMenuList){
				if(menu) menu.close();
			} 
		}
		// 버튼하고 서브 메뉴하고 추가.
		public final function add(button:InteractiveObject, menu:Menu = null): void
		{
			if(this.numChildren != 0){
				var lastChild:DisplayObject = this.getChildAt(this.numChildren-1);
				if(layout.direction == 'horizontal') button.x = lastChild.x+lastChild.width+layout.space;
				else button.y = lastChild.y+lastChild.height+layout.space;
			}
			addChild(button);
			subMenuList.push(menu);
			if(!menu) return;
			button.addEventListener(MouseEvent.ROLL_OVER, closeAllSub );
			button.addEventListener(MouseEvent.ROLL_OVER, menu.open );
		}
		
		// 트위너를 위한 도우미 메서드.
		private function enabledVisible(): void { this.visible = true; }
		private function disabledVisible(): void  { this.visible = false; }
	}//c
}